import numpy as np
import torch


def _validate_vector(u, dtype=None):
    # XXX Is order='c' really necessary?//
    u = np.asarray(u, dtype=dtype, order='c').squeeze()
    # Ensure values such as u=1 and u=[1] still return 1-D arrays.
    u = np.atleast_1d(u)
    if u.ndim > 1:
        raise ValueError("Input vector should be 1-D.")
    return u

def mahalanobis(u, v, VI):
   
    u = _validate_vector(u)
    v = _validate_vector(v)
    VI = np.atleast_2d(VI)
    delta = u - v
    m = np.dot(np.dot(delta, VI), delta)
    return np.sqrt(m)


def tensor_mahalanobis(u,v,i):
    u=u.unsqueeze(1)
    v=v.unsqueeze(2)
    a=torch.matmul(torch.matmul(u,i),v)
    return a
# u=torch.tensor([[1,2,3],[1,2,3]])
# v=torch.tensor([[0,1,0],[0,1,0]])
# i=torch.tensor([[[1, 2, 3], [5, 1, 5], [5, 5, 1]],[[1, 2, 3], [5, 1, 5], [5, 5, 1]]])
# print(tensor_mahalanobis(u,v,i))



def mul_mahalanobios(u,v,i):
    tp=u-v
#     u=np.expand_dims(u,axis=1)
    tp1=np.expand_dims(tp,axis=1)
    tp2=np.expand_dims(tp,axis=2)
#     print(tp1.shape,tp2.shape)
    x=np.matmul(tp1,i)
#     print(x.shape)
    return np.sqrt(np.matmul(x,tp2))